import { Message } from './intenface'

const url = 'wss://service-qgnrlvfs-1300852544.gz.apigw.tencentcs.com/release'

export class myWebSocket {
  ws: WebSocket
  message: Message
  onmessageFn: (this: myWebSocket, event: MessageEvent) => any

  constructor(onmessageFn: (this: myWebSocket, event: MessageEvent) => any) {
    this.ws = new WebSocket(url)
    this.ws.onopen = (evt) => {
      console.log("Connection open ...")
      this.ws.send(``)
    }

    this.onmessageFn = onmessageFn
    this.ws.onmessage = (e) => {
      this.onmessageFn(e)
    }

    this.ws.onclose = function (e) {
      console.log("Connection closed.");
    };

    this.ws.onerror = (e) => {
      console.error(e)
    }
    this.message = {
      clientID: -1,
      opponentID: -1,
      roomID: -1,
      key: ``,
      x: -1,
      y: -1,
      msg: ``,
      player: true,
      canStart: false,
      opponentQuit: false,
      talk: ``,
      canOpponentRegret: 0
    }
  }

  sendMessage() {
    let sendMsg = JSON.stringify(this.message);
    sendMsg = sendMsg.replace(/\"/g, `\\"`);
    this.ws.send(sendMsg); // 复杂的数据结构要先进行序列化
  }
}